package servlet;

import dao.UserDao;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhangYufei
 * Date: 2021-07-21
 * Time: 15:03
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf8");

        // 1. 从 req 读取用户提交的 username 和 password
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if("".equals(username) || "".equals(password) || username == null || password == null){
            resp.setStatus(404);
            resp.getWriter().write("<h3>用户名或者密码不能为空</h3>");
            return;
        }

        // 2. 从数据库中查找指定用户名的用户信息.
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if(user == null){
            resp.sendError(404, "用户名或者密码错误");
            return;
        }
        if(!password.equals(user.getPassword())){
            resp.sendError(404, "用户名或者密码错误");
            return;
        }

        /*resp.setStatus(200);
        resp.getWriter().write("<h3>登录成功</h3>");*/
        // 3. 登陆成功! 创建会话.
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        // 4. 直接把用户页面重定向到博客列表页.
        resp.sendRedirect("blogList");
    }
}
